/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.linzuo.generatorsql.demos.web;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import cn.hutool.extra.tokenizer.Result;
import cn.hutool.extra.tokenizer.TokenizerEngine;
import cn.hutool.extra.tokenizer.Word;
import cn.hutool.extra.tokenizer.engine.hanlp.HanLPEngine;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.linzuo.generatorsql.demos.util.TranslatorUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {

    @PostMapping("/gen")
    @ResponseBody
    public String gen(MultipartFile file) throws IOException {
        Dict dict = Dict.create();
        String originName = file.getOriginalFilename();
        String tableEn = TranslatorUtils.getTranslateResult(originName);
        if(tableEn.equals(originName)){
            tableEn="T"+ DateUtil.formatDate(new Date());
        }
        dict.set("tableName",tableEn);
        dict.set("tableComment",file.getOriginalFilename());
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<List<Object>> all = reader.read();
        if (CollectionUtil.isEmpty(all)){
            return null;
        }
        List<Object> firstRow = all.get(0);
        List<Dict> colList = new ArrayList<>();
        firstRow.stream().forEach(first->{
            String comment = String.valueOf(first).trim();
            String name = trans(comment).trim();
            colList.add(new Dict().set("name",name).set("comment",comment).set("len",0));
        });
        for (int i = 1; i < all.size(); i++) {
            List<Object> row = all.get(i);
            for (int i1 = 0; i1 < row.size(); i1++) {
                String rowCol = StrUtil.toString(row.get(i1));
                Integer max = colList.get(i1).getInt("len");
                if(max<rowCol.length()){
                    colList.get(i1).set("len",rowCol.length());
                }
            }
        }
        dict.set("colList",colList);
        return getTemplate(dict);
    }

    private String trans(String text) {
        TokenizerEngine engine = new HanLPEngine();
        //解析文本
        Result result = engine.parse(text);
        Iterator<Word> iterator = result.iterator();
        StringBuffer stringBuffer = new StringBuffer();
        while(iterator.hasNext()){
            Word a = iterator.next();
            String rs = TranslatorUtils.getTranslateResult(String.valueOf(a));
            stringBuffer.append(rs);
        }
        return stringBuffer.toString();
    }

    private String getTemplate(Dict dict){
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
        Template template = engine.getTemplate("generator-sql.vm");
        String result = template.render(dict);
        return result;
    }
}
